#!/usr/bin/php -q
<?php

$DEBUG = true;

// fine mozilla dir
$mozDir = "/usr/lib/mozilla";
$dirs = glob("/usr/lib/mozilla*");
usort($dirs,'mozSort');
$mozDir = array_pop($dirs);

function mozSort($a,$b) {
	return version_compare(getVer($a),getVer($b));
}
function getVer($in) {
	if (preg_match('/mozilla-seamonkey-(.*)/',$in,$match)) {
		return $match[1];
	}
	else if (preg_match('/mozilla-(.*)/',$in,$match)) {
		return $match[1];
	}
	return 0;
}

$tmp = getenv('MOZ_LIB');
if ($tmp) {
	$mozDir = $tmp;
}

putenv( "LD_LIBRARY_PATH=$mozDir" );
putenv( "DISPLAY=:10" );

/*if (!isset($argv[1]) || !isset($argv[2])) {
	echo "Usage: PagePrint url outputfile\n";
	die(1);
}*/
if (!isset($argv[1]) || !isset($argv[2])) {
        echo "Usage: PagePrint [--snapshot] [-print] [-p printer_name] [-o lpr-option] url outputfile\n";
        die(1);
}

if ($argc > 1) {
	$url = $argv[$argc-2];
	$outFile = $argv[$argc-1];
}

$snapshot = '';
if (array_search('-s',$argv) || array_search('--snapshot',$argv)) {
	$snapshot = 'snapshot';
}

$print = false;
$printargs = '';
for($i = 2;$i < count($argv);$i++) {
        if($argv[$i] == '-print') {
                $print = true;
                $snapshot=false;
        }
        if($argv[$i] == '-p') {
                $print = true;
                $snapshot = false;
                $printargs .= " -P ".$argv[++$i];
        }
        if($argv[$i] == '-o') {
                $printargs .= " -o ".$argv[++$i];
        }
}

$dir = dirname(__FILE__);

$procUniq = uniqid('PagePrint');
$tmp = $argv;
unset($tmp[0]);
$args = implode(' ',$tmp);

// cookie hack
$cookieHack = '';
if ($print && session_id() != '') {
	$cookieHack = " -hn set-cookie -hv ".session_id()." ";
}
$command = "$dir/PagePrint-bin -i $procUniq $cookieHack$args 2>&1";
var_dump($command);
$handle = popen($command, "r");

//notice("Loading URL and Snapshoting\n");
while(!feof($handle)) {
	$line = fgets($handle,1024);

	if ($DEBUG) {
		notice($line);
	}
	else {
		notice('*');
	}

	if (preg_match('/ps file: (.+)/',$line,$match)) {
		$psFile = $match[1];
		notice("\nWaiting for ps file to be fully written\n");
		$lsof = true;
		while($lsof) {
			$lsof = shell_exec("/usr/sbin/lsof $psFile");
		}

		notice("PS file is: ".formatSize(filesize($psFile))."\n");
		notice("Closing Mozilla\n");

		$procs = shell_exec("ps x | grep \"$procUniq\" | grep -v \"grep\"");
		if (preg_match('/([0-9]+) /',$procs,$match)) {
			shell_exec("kill $match[1]");
		}
		else {
			error("Houston we have a problem, I couldn't find my Mozilla process to kill\n");
		}
		break;
	}
}


pclose($handle);

if ($print) {
        $command = "/usr/bin/lpr $printargs $psFile";
        var_dump($command);
        passthru($command);
} elseif (!$snapshot) {
        notice("Converting PS to PDF\n");
        $command = "/usr/bin/ps2pdf $psFile $outFile";
        // generate pdf
        passthru($command);

        unlink($psFile);
}




// util functions
function formatSize($size)
{
   $count = 0;
   $format = array("B","KB","MB","GB","TB","PB","EB","ZB","YB");
   while(($size/1024)>1 && $count<8)
   {
       $size=$size/1024;
       $count++;
   }
   $return = number_format($size,0,'','.')." ".$format[$count];
   return $return;
}

function notice($in) {
	echo $in;
}
function error($in) {
	echo $in;
}
?>
